package com.carp.springframework.beans.factory.support;

import com.carp.springframework.beans.BeansException;
import com.carp.springframework.beans.factory.DisposableBean;
import com.carp.springframework.beans.factory.config.SingletonBeanRegistry;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lile
 * @date 2023/2/2
 */
public class DefaultSingletonBeanRegistry implements SingletonBeanRegistry {

    private final Map<String, Object> singletonMap = new ConcurrentHashMap<>();

    private final Map<String, DisposableBean> disposableBeans = new HashMap<>();

    @Override
    public Object getSingleton(String beanName) {
        return singletonMap.get(beanName);
    }

    protected void addSingleton(String beanName, Object singletonObject) {
        singletonMap.put(beanName, singletonObject);
    }

    protected void registerDisposableBean(String beanName, DisposableBean bean) {
        disposableBeans.put(beanName, bean);
    }

    public void destroySingletons() {
        Iterator<Map.Entry<String, DisposableBean>> iterator = disposableBeans.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, DisposableBean> entry = iterator.next();
            iterator.remove();
            try {
                entry.getValue().destroy();
            } catch (Exception e) {
                throw new BeansException("Destroy method on bean with name '" + entry.getKey() + "' threw an exception", e);
            }
        }
    }

}
